package parse;

import java.util.*;

import RecordManagement.*;
import SystemManagement.*;
import Type.*;
import ExecuteEngine.*;

public class Insert extends SQL{
	private TableName table_name;
	private Value_list v;
	private Tuple t;
	private RM_FileHandle fileHandle;
	
	public Insert(String name, Value_list v){
		this.table_name = new TableName(name);
		this.v = v;
	}
	
	public TableName GetTableName(){
		return this.table_name;
	}
	
	public Value_list GetValues(){
		return this.v;
	}
	
	public void insertTuple(RM_Manager rm, SM_Manager sm){
		try{
			fileHandle = rm.OpenFile(table_name.GetTableName());			
		}
		catch(java.io.IOException e){
			
		}
		
		DataItem tuple[] = new DataItem[v.value_list.size()];
    	List<DataAttrInfo> info = new ArrayList<DataAttrInfo>();
    	sm.GetDataAttrInfo(table_name.GetTableName(), info);
    	
    	if(info.size() != v.value_list.size()){
    		System.out.println("The value list is invalid...");
    		return;
    	}
    	
    	for(int i=0; i<v.value_list.size(); i++){
    		tuple[i] = v.value_list.get(i).v;
    		if(tuple[i] instanceof VarcharItem)
    			((VarcharItem)tuple[i]).value.setLength(info.get(i).attrLength);
    	}
    	
		fileHandle.InsertRec(t.tupleToByte(tuple));
		rm.CloseFile(fileHandle);
	}
}